<template>
	<!-- 借阅卡管理 -->
	<view class="sharedBookstore_borrowingCard">
		<!-- 未绑定样式 -->
		<view class="w-full sharedBookstore_borrowingCard_unboundBox" v-if="!cardsInfo.reader_code">
			<view class="sharedBookstore_borrowingCard_unboundBox_topBox">
				<image
					class="sharedBookstore_borrowingCard_unboundBox_topBoxIMG"
					:src="baseImg + '/BorrowingCard/BorrowingCard_WBD.png'"
				></image>
				<text
					class="text-[#ffffff] text-[60rpx]"
					style="
						position: absolute;
						z-index: 2;
						display: block;
						float: left;
						width: 100%;
						height: 410rpx;
						line-height: 410rpx;
						text-align: center;
					"
					>未绑卡</text
				>
			</view>
			<view class="sharedBookstore_borrowingCard_unboundBox_middleBox">
				<view class="viewsharedBookstore_borrowingCard_unboundBox_middleBox_searchBox">
					<input
						type="text"
						:value="cardNumber"
						placeholder="请输入卡号"
						placeholder-class="input-placeholder"
						@input="inputCardNumber"
					/>
					<image :src="baseImg + '/BorrowingCard/BorrowingCard_sys.png'" @tap="wxScan"></image>
				</view>
				<view
					class="viewsharedBookstore_borrowingCard_unboundBox_middleBox_bntBox"
					@tap="bindCardInfo"
				>
					<image :src="baseImg + '/BorrowingCard/BorrowingCard_bnt.png'"></image>
					<text>绑定借阅卡</text>
				</view>
			</view>
		</view>

		<!-- 绑定样式 -->
		<view class="w-full sharedBookstore_borrowingCard_bindBox" v-if="cardsInfo.reader_code">
			<view class="sharedBookstore_borrowingCard_bindBox_topBox">
				<image
					class="sharedBookstore_borrowingCard_bindBox_topBoxIMG"
					:src="baseImg + '/BorrowingCard/BorrowingCard_bd.png'"
				></image>
				<view class="sharedBookstore_borrowingCard_bindBox_topBox_textBox">
					<view class="sharedBookstore_borrowingCard_bindBox_topBox_textBox_top"
						>{{ cardsInfo.reader_code_organization }}<text>{{ cardsInfo.reader_code_class }}</text
						>{{ cardsInfo.reader_code_name }}</view
					>
					<view class="sharedBookstore_borrowingCard_bindBox_topBox_textBox_middle"
						>校园图书借阅卡</view
					>
					<view class="sharedBookstore_borrowingCard_bindBox_topBox_textBox_bottom">
						<text style="float: left; width: 200rpx; overflow: hidden; text-overflow: ellipsis"
							>NO.{{ cardsInfo.reader_code }}</text
						>
						<text style="float: right"
							>{{ formatTime(cardsInfo.end_time, '年月日', false) }}到期</text
						>
					</view>
				</view>
			</view>
			<view
				class="sharedBookstore_borrowingCard_bindBox_middleBox sharedBookstore_borrowingCard_bindBox_bindStudent"
			>
				<view class="top">绑定学生：{{ userInfo.username }}</view>
				<view class="bot"
					>{{ userInfo.school_name }} <block v-if="userInfo.class_name">/</block>
					{{ userInfo.class_name }}</view
				>
			</view>
			<view class="sharedBookstore_borrowingCard_bindBox_middleBox">
				<view class="sharedBookstore_borrowingCard_bindBox_middleBox_left" @tap="UnbindModal(true)">
					<image :src="baseImg + '/BorrowingCard/BorrowingCard_jbBNT.png'"></image>
					<text>解绑</text>
				</view>
				<view
					class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
					@tap="reportingLossModal(true)"
				>
					<image :src="baseImg + '/BorrowingCard/BorrowingCard_jbBNT.png'"></image>
					<text>挂失</text>
				</view>
			</view>
		</view>

		<view class="sharedBookstore_borrowingCard_unboundBox_bottomBox">
			<text>温馨提示： </text>
			<text
				>1.请输入借阅卡号，或扫码绑定。一张借阅卡只能绑定一个学生用户，卡片绑定后不可转赠他人。
			</text>
			<text> 2. 请妥善保管您的借阅卡，如有遗失，请第一时间在本界面挂失，以免他人盗用。 </text>
			<text> 3. 若您需要更换绑定的卡片，请先“解绑”旧卡，再绑定新的卡片。 </text>
		</view>
	</view>

	<!-- 显示学生信息弹窗 -->
	<uni-popup ref="popup" :mask-click="false" background-color="none">
		<view class="w-full px-4 box-border">
			<view class="w-full rounded-[54rpx] rule-modal relative px-6 py-6 box-border">
				<view class="w-full relative">
					<image
						:src="baseImg + '/close-btn.png'"
						class="w-[44rpx] h-[44rpx] absolute right-0 top-0"
						@tap="ruleModal(false)"
					></image>
					<view class="text-center text-[#303030] text-[34rpx] font-bold">请核对绑定信息 </view>
					<view class="w-full mt-6 bg-white rounded-[30rpx] px-[30rpx] box-border rule-box">
						<view class="studentInformation_middleBox studentInformation_middleBoxTop">
							<view class="studentInformation_middleBox_text top"><text>卡片信息</text></view>
							<view class="studentInformation_middleBox_text"
								>{{ cardsInfo.reader_code_organization }} {{ cardsInfo.reader_code_class }}
								{{ cardsInfo.reader_code_name }}</view
							>
						</view>
						<view class="studentInformation_middleBox">
							<view class="studentInformation_middleBox_text top"><text>倍阅读学生信息</text></view>
							<view class="studentInformation_middleBox_text"
								><text>学校</text>{{ currentChoose.school_name }}</view
							>
							<view class="studentInformation_middleBox_text"
								><text>班级</text>{{ currentChoose.class_name }}</view
							>
							<view class="studentInformation_middleBox_text"
								><text>姓名</text>{{ currentChoose.username }}</view
							>
							<view
								class="w-full mt-[30rpx] studentInformation"
								@tap="switchModal(true)"
								v-if="studentList && studentList.length > 1"
							>
								<text>切换学生</text>
							</view>
						</view>
						<view class="studentInformation_bottomBox">
							<view class="sharedBookstore_borrowingCard_bindBox_middleBox">
								<view
									class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
									@tap="ruleModal(false)"
								>
									<image :src="baseImg + '/BorrowingCard/BorrowingCard_tc_qxBnt.png'"></image>
									<text>取消</text>
								</view>
								<view
									class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
									@tap="confirmBindCard"
								>
									<image :src="baseImg + '/BorrowingCard/BorrowingCard_tc_qrBnt.png'"></image>
									<text style="color: #f4f7f4">绑定</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</uni-popup>

	<!-- 切换学生信息弹窗 -->
	<uni-popup ref="popup1" :mask-click="false" background-color="none">
		<view class="w-full px-4 box-border">
			<view class="w-full rounded-[54rpx] rule-modal relative px-6 py-6 box-border">
				<view class="w-full relative">
					<image
						:src="baseImg + '/close-btn.png'"
						class="w-[44rpx] h-[44rpx] absolute right-0 top-0"
						@tap="switchModal(false)"
					></image>
					<view class="text-center text-[#303030] text-[34rpx] font-bold">切换学生</view>
					<view class="w-full mt-6 bg-white rounded-[30rpx] px-[30rpx] box-border rule-box">
						<view class="w-full mt-[60rpx]">
							<view
								class="w-full h-[167rpx] relative mb-4"
								v-for="(item, index) in studentList"
								:key="item.student_id"
							>
								<view
									class="w-full h-[167rpx] px-4 py-4 box-border rounded-[83rpx] flex justify-between items-center"
									style="background: #fff3f3"
									@tap="change(index)"
								>
									<view class="flex justify-between items-center">
										<image
											class="w-[102rpx] h-[102rpx] rounded-[50%] border-1 border-solid border-[#fff] mr-1"
											:src="baseImg + '/user-default.png'"
										></image>
										<view class="flex flex-col pl-2 py-4">
											<text class="text-[#303030] text-[33rpx]">{{ item.username }}</text>
											<text class="text-[#5E5E5E] text-[24rpx] mt-[10rpx]">{{
												item.school_name
											}}</text>
											<text class="text-[#5E5E5E] text-[24rpx] mt-[10rpx]">{{
												item.class_name
											}}</text>
										</view>
									</view>
									<radio
										:checked="item.is_default === 1"
										v-if="item.is_default === 1"
										color="#6FA5F3"
									></radio>
								</view>
							</view>
							<!-- <view class="w-full h-[167rpx] relative mb-4">
								<view
									class="w-full h-[167rpx] px-4 py-4 box-border rounded-[83rpx] flex justify-between items-center"
									style="background: #e7f0fd"
								>
									<view class="flex justify-between items-center">
										<image
											class="w-[102rpx] h-[102rpx] rounded-[50%] border-1 border-solid border-[#fff] mr-1"
											:src="baseImg + '/user-default.png'"
										></image>
										<view class="flex flex-col pl-2 py-4">
											<text class="text-[#303030] text-[33rpx]">谢安琪</text>
											<text class="text-[#5E5E5E] text-[24rpx] mt-[10rpx]">长江实验小学</text>
											<text class="text-[#5E5E5E] text-[24rpx] mt-[10rpx]">三年级1班</text>
										</view>
									</view>
									<radio color="#6FA5F3"></radio>
								</view>
							</view> -->
						</view>
						<!-- <view class="studentInformation_bottomBox" style="margin-top: 50rpx">
								<view class="sharedBookstore_borrowingCard_bindBox_middleBox">
									<view
										class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
										@tap="switchModal(false)"
									>
										<image src="/static/BorrowingCard_tc_qxBnt.png"></image>
										<text>取消</text>
									</view>
									<view class="sharedBookstore_borrowingCard_bindBox_middleBox_left">
										<image src="/static/BorrowingCard_tc_qrBnt.png"></image>
										<text style="color: #f4f7f4">确认</text>
									</view>
								</view>
							</view> -->
					</view>
				</view>
			</view>
		</view>
	</uni-popup>

	<!-- 解绑弹窗 -->
	<uni-popup ref="popup2" :mask-click="false" background-color="none">
		<view class="w-full px-4 box-border">
			<view class="w-full rounded-[54rpx] rule-modal relative px-6 py-6 box-border">
				<view class="w-full relative">
					<image
						:src="baseImg + '/close-btn.png'"
						class="w-[44rpx] h-[44rpx] absolute right-0 top-0"
						@tap="UnbindModal(false)"
					></image>
					<view class="text-center text-[#303030] text-[34rpx] font-bold">提示</view>
					<view class="w-full mt-6 bg-white rounded-[30rpx] px-[30rpx] box-border rule-box">
						<view
							class="mt-[100rpx] text-[32rpx] px-[30rpx] text-[#3B3B3B]"
							style="width: clac(100% - 60rpx); line-height: 60rpx"
							>确定将借阅卡与该学生解除绑定吗？</view
						>
						<view class="studentInformation_bottomBox">
							<view class="sharedBookstore_borrowingCard_bindBox_middleBox">
								<view
									class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
									@tap="unbindCardInfo"
								>
									<image :src="baseImg + '/BorrowingCard/BorrowingCard_tc_qrBnt.png'"></image>
									<text style="color: #f4f7f4">确认解绑</text>
								</view>
								<view
									class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
									@tap="UnbindModal(false)"
								>
									<image :src="baseImg + '/BorrowingCard/BorrowingCard_tc_qxBnt.png'"></image>
									<text>取消</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</uni-popup>

	<!-- 挂失弹窗 -->
	<uni-popup ref="popup3" :mask-click="false" background-color="none">
		<view class="w-full px-4 box-border">
			<view class="w-full rounded-[54rpx] rule-modal relative px-6 py-6 box-border">
				<view class="w-full relative">
					<image
						:src="baseImg + '/close-btn.png'"
						class="w-[44rpx] h-[44rpx] absolute right-0 top-0"
						@tap="reportingLossModal(false)"
					></image>
					<view class="text-center text-[#303030] text-[34rpx] font-bold">提示</view>
					<view class="w-full mt-6 bg-white rounded-[30rpx] px-[30rpx] box-border rule-box">
						<view
							class="mt-[100rpx] text-[32rpx] px-[30rpx] text-[#3B3B3B]"
							style="width: clac(100% - 60rpx); line-height: 60rpx"
							>确定挂失该卡片吗？挂失后该借 阅卡将不可再使用！
						</view>
						<view class="studentInformation_bottomBox">
							<view class="sharedBookstore_borrowingCard_bindBox_middleBox">
								<view
									class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
									@tap="lossCardInfo"
								>
									<image :src="baseImg + '/BorrowingCard/BorrowingCard_tc_qrBnt.png'"></image>
									<text style="color: #f4f7f4">确认挂失</text>
								</view>
								<view
									class="sharedBookstore_borrowingCard_bindBox_middleBox_left"
									@tap="reportingLossModal(false)"
								>
									<image :src="baseImg + '/BorrowingCard/BorrowingCard_tc_qxBnt.png'"></image>
									<text>取消</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store';
import { debounce, formatTime } from '@/utils/index';
import {
	ShareBook,
	bindCardInfoApi,
	getCardInfoApi,
	lostCardInfoApi,
	unbindCardInfoApi,
	validCardInfoApi,
} from '@/service/shareBookStore';
import { getDefaultUserInfo, getStudentList, setDefaultUserInfo } from '@/service/user';

const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);

const popup = ref(null);
const popup1 = ref(null);
const popup2 = ref(null);
const popup3 = ref(null);

// 学生信息弹窗
const ruleModal = flag => {
	if (flag) {
		popup.value.open();
		getStuList();
	} else {
		popup.value.close();

		currentChoose.value.class_name = userInfo.value.class_name;
		currentChoose.value.school_name = userInfo.value.school_name;
		currentChoose.value.username = userInfo.value.username;
		currentChoose.value.student_id = userInfo.value.student_id;
	}
};

// 切换学生弹窗
const switchModal = flag => {
	if (flag) {
		popup1.value.open();
		popup.value.close();

		currentChoose.value.class_name = userInfo.value.class_name;
		currentChoose.value.school_name = userInfo.value.school_name;
		currentChoose.value.username = userInfo.value.username;
		currentChoose.value.student_id = userInfo.value.student_id;
	} else {
		popup1.value.close();
		popup.value.open();
	}
};

// 确认解绑弹窗
const UnbindModal = flag => {
	if (flag) {
		popup2.value.open();
	} else {
		popup2.value.close();
	}
};

// 确认挂失弹窗
const reportingLossModal = flag => {
	if (flag) {
		popup3.value.open();
	} else {
		popup3.value.close();
	}
};

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const cardsInfo = ref<ShareBook.CardData>({
	reader_code: '',
	end_time: 0,
	reader_code_name: '',
	reader_code_organization: '',
	reader_code_class: '',
});

const getCardInfo = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await getCardInfoApi({
			student_id: userInfo.value.student_id,
		});
		uni.hideLoading();
		// console.log('====》res', res);
		if (res.status_code === 200 && res.data) {
			cardsInfo.value = res.data;
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '网络请求失败，请稍后再试',
		});
	}
};
const unbindCardInfo = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await unbindCardInfoApi({
			student_id: userInfo.value.student_id,
			reader_code: cardsInfo.value.reader_code,
		});
		uni.hideLoading();
		// console.log('====》res', res);
		if (res.status_code === 200) {
			uni.showToast({
				icon: 'none',
				title: '解除成功',
			});
			popup2.value.close();
			setTimeout(() => {
				// 延时获取卡的信息
				getCardInfo();
			}, 1000);
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
			popup2.value.close();
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '网络请求失败，请稍后再试',
		});
		popup2.value.close();
	}
};

const lossCardInfo = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await lostCardInfoApi({
			student_id: userInfo.value.student_id,
			reader_code: cardsInfo.value.reader_code,
		});
		uni.hideLoading();
		// console.log('====》res', res);
		if (res.status_code === 200 && res.data) {
			uni.showToast({
				icon: 'none',
				title: '挂失成功',
			});
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '网络请求失败，请稍后再试',
		});
	}
};

const cardNumber = ref('');
const wxScan = () => {
	uni.scanCode({
		success: res => {
			console.log('=====>', res.result); // 扫码的结果，具体格式根据扫描的内容有所不同，一般是字符串形式

			cardNumber.value = res.result;
		},
		fail: () => {
			// console.log('扫码失败');
			uni.showToast({
				icon: 'none',
				title: '扫码失败，请稍后再试',
			});
		},
	});
};

const validCardInfo = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await validCardInfoApi({
			student_id: userInfo.value.student_id,
			reader_code: cardNumber.value,
		});
		uni.hideLoading();
		// console.log('====》res', res);
		if (res.status_code === 200 && res.data) {
			cardsInfo.value = { ...cardsInfo.value, ...res.data };

			ruleModal(true); // 弹出确认绑定的学生
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '网络请求失败，请稍后再试',
		});
	}
};

const bindCardInfo = () => {
	console.log('====>cardNumber', cardNumber.value);

	if (!cardNumber.value.trim()) {
		uni.showToast({
			icon: 'none',
			title: '请先输入卡号或者扫码',
		});
		return false;
	}
	return validCardInfo(); // 判断卡号
};

const confirmBindCard = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await bindCardInfoApi({
			student_id: currentChoose.value.student_id,
			reader_code: cardNumber.value,
		});
		uni.hideLoading();
		console.log('====confirmBindCard', res);
		if (res.status_code === 200) {
			uni.showToast({
				icon: 'none',
				title: '绑定成功',
			});
			cardNumber.value = '';
			setTimeout(() => {
				// 延时获取卡的信息
				getCardInfo();
			}, 1000);

			await setDefaultUserInfo(currentChoose.value.student_id);
			popup.value.close();
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
			popup.value.close();
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '网络请求失败，请稍后再试',
		});
		popup.value.close();
	}
};

const studentList = ref();
const getStuList = async () => {
	uni.showLoading({
		title: '加载中...',
	});
	try {
		const res = await getStudentList();
		uni.hideLoading();
		if (res.status_code === 200 && res.data) {
			studentList.value = res.data;
		}
		const defaultUser = await getDefaultUserInfo();
		if (defaultUser.status_code === 200) {
			userStore.setUserInfo(defaultUser.data);
		}
	} catch (error) {
		uni.hideLoading();
	}
};
// const confirmChooseStu = async item => {
// 	if (!showAdd) {
// 		uni.showToast({
// 			icon: 'none',
// 			title: '请选择默认账户',
// 		});
// 		return;
// 	}
// 	const obj = studentList.value.find(item => item.is_default === 1);
// 	if (!obj) return;
// 	if (obj.student_id === userInfo.value.student_id) {
// 		return;
// 	}
// 	try {
// 		const res = await setDefaultUserInfo(obj.student_id);
// 		if (res.status_code === 200) {
// 			uni.showToast({
// 				icon: 'none',
// 				title: '设置成功',
// 				success: async () => {
// 					getStuList();
// 				},
// 			});
// 		} else {
// 			uni.showToast({
// 				icon: 'none',
// 				title: res.message,
// 			});
// 		}
// 	} catch (error) {
// 		uni.showToast({
// 			icon: 'none',
// 			title: '服务器异常',
// 		});
// 	}
// };
const currentChoose = ref({
	school_name: userInfo.value.school_name,
	class_name: userInfo.value.class_name,
	username: userInfo.value.username,
	student_id: userInfo.value.student_id,
});
const change = index => {
	studentList.value = studentList.value.map((item, windex) => {
		const obj = Object.assign(item);
		obj.is_default = 0;
		if (windex === index) {
			obj.is_default = 1;
			currentChoose.value.class_name = item.class_name;
			currentChoose.value.school_name = item.school_name;
			currentChoose.value.username = item.username;
			currentChoose.value.student_id = item.student_id;
		}
		return obj;
	});
	popup1.value.close();
	popup.value.open();
};

const inputCardNumber = debounce(e => {
	// 防抖
	cardNumber.value = e.detail.value;
}, 500);

onShow(() => {
	getCardInfo();
});

defineExpose({
	getCardInfo,
});
</script>

<style lang="scss" scoped>
.sharedBookstore_borrowingCard_bindBox_bindStudent {
	box-sizing: border-box;
	padding: 24rpx 44rpx;
	margin-top: 28rpx !important;
	font-size: 29rpx;
	line-height: 54rpx;
	color: #3b3b3b;
	background: #f3f3f5;
	border-radius: 28rpx;
}

.studentInformation_middleBox {
	position: relative;
	z-index: 1;
	box-sizing: border-box;
	padding: 20rpx 25rpx;
	font-size: 26rpx;
	line-height: 55rpx;
	color: #3b3b3b;
	background: #e7f0fd;
	border-radius: 21rpx;

	&.studentInformation_middleBoxTop {
		margin-top: 35rpx;
		margin-bottom: 21rpx;
	}

	.studentInformation_middleBox_text {
		margin-top: 0rpx;
		margin-bottom: 18rpx;
	}

	.top {
		margin-bottom: 30rpx;
		font-size: 32rpx;
	}

	.studentInformation {
		position: absolute;
		right: 20rpx;
		bottom: 50rpx;
		z-index: 5;
	}
}
</style>
